package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.Employee;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    private final CategoryMapper categoryMapper;
    private final DishMapper dishMapper;
    private final SetmealMapper setmealMapper;

    @Override
    public List<Category> getByType(Integer type) {
        List<Category> list = categoryMapper.getByType(type);
        return list;
    }

    @Override
    public void setStatus(int status, Long id) {
        categoryMapper.setStatus(status, id);
    }

    @Override
    public void update(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        categoryMapper.update(category);
    }

    @Autowired
    public CategoryServiceImpl(CategoryMapper categoryMapper, DishMapper dishMapper, SetmealMapper setmealMapper){
        this.categoryMapper = categoryMapper;
        this.dishMapper = dishMapper;
        this.setmealMapper = setmealMapper;
    }

    @Override
    public void add(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);

        // 添加各项属性
        category.setStatus(0);

        // 修改人员
        Long id = BaseContext.getCurrentId();
        category.setCreateUser(id);
        category.setUpdateUser(id);

        categoryMapper.insert(category);
    }

    @Override
    public PageResult pageQuery(CategoryPageQueryDTO categoryPageQueryDTO) {
        PageHelper.startPage(categoryPageQueryDTO.getPage(), categoryPageQueryDTO.getPageSize());

        try (Page<Category> page = categoryMapper.pageQuery(categoryPageQueryDTO)) {
            return new PageResult(page.getTotal(), page.getResult());
        }
    }

    @Override
    public void deleteById(Long id) {
        // 查询下面是否有菜品
        List<Dish> dishes = dishMapper.getByCategoryId(id);
        List<Setmeal> setmeals = setmealMapper.getByCategoryId(id);

        // 判断是否为空
        if (!dishes.isEmpty() || !setmeals.isEmpty()){
            throw new DeletionNotAllowedException("该分类下还有菜品，当前不可删除");
        }

        categoryMapper.deleteById(id);
    }
}
